package com.education.demouse.excel;

import com.alibaba.excel.annotation.ExcelProperty;
import com.education.demouse.excel.annotation.ExcelValid;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * @Author: liftsail
 * @Date: 2022/10/17 11:21
 * @Description: 不积跬步无以至千里
 * Excel导入字段校验
 */
public class ExcelImportValid {

    /**
     * Excel导入字段校验
     *
     * @param object 校验的JavaBean 其属性须有自定义注解
     */
    public static void valid(Object object) throws ExceptionCustom {
        //得到对象的字段列表
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            //设置可访问
            field.setAccessible(true);
            //属性的值
            Object fieldValue = null;
            //得到字段上的ExcelValid注解-有注解意味字段不能为null
            boolean isExcelValid = field.isAnnotationPresent(ExcelValid.class);
            if (isExcelValid) {
                ExcelValid excelValid = field.getAnnotation(ExcelValid.class);
                try {
                    //得到对象属性的value值
                    fieldValue = field.get(object);
                } catch (IllegalAccessException e) {
                    throw new ExceptionCustom("IMPORT_PARAM_CHECK_FAIL", "导入参数检查失败");
                }

                if (Objects.isNull(fieldValue)) {
                    throw new ExceptionCustom("NULL", field.getAnnotation(ExcelValid.class).message());
                }

                //获取注解的length属性
                int length = field.getAnnotation(ExcelValid.class).length();
                int actlength = Integer.valueOf(String.valueOf(fieldValue).length()).intValue();
                if (length != 0 && length != actlength) {
                    String[] value = field.getAnnotation(ExcelProperty.class).value();
                    StringBuffer stringBuffer = new StringBuffer();
                    for (String s : value) {
                        stringBuffer.append(s);
                    }
                    throw new ExceptionCustom("NULL", stringBuffer.toString() + "输入位数有误,应当" + length + "位,实际" + actlength + "位");
                }
            }
        }
    }
}